package com.shiro;

import com.service.PermissionService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 具体权限控制
 */
@Component
public class UsernameRealm extends AuthorizingRealm {

    @Autowired
    private PermissionService permissionService;

    private List<String> wuyePermission = Arrays.asList("/qiye/wy_addqiye" , "/upload" , "/qiye/wy_selectqiye" , "/qiye/updateqiye" , "/wuye/selectwuyestatus" , "/staff/wy_addstaff" , "/qiye/wy_selectqiyestatus" , "/qiye/upStatus" , "/country/selectCountry" , "/staff/sfzShifouExist") ;


    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof UsernameAuth;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String tokenString = principalCollection.toString();
        String username = tokenString;
         List<String> list = permissionService.getPermissionByUser(username);
//        System.out.println(list);
//         list.add("/admin/permission/findAllPermission") ;
//         list.add("/admin/permission/findPermissionByRole") ;
//         list.add("/admin/permission/PermissionDel") ;
//         list.add("/admin/permission/PermissionFindById") ;
//         list.add("/admin/permission/PermissionUpdate") ;
//         list.add("/admin/permission/saveOrDelPermissionByRole") ;
//         list.add("/admin/permission/savePermission") ;
        //strs.removeAll(Collections.singleton(null));
        if("*&**&wuye".equals(username)) {
            simpleAuthorizationInfo.addStringPermissions(wuyePermission);
        }
        simpleAuthorizationInfo.addStringPermissions(list);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        String username = token;
        //Admin admin = iadminService.getAdminByUserName(username);
        //if (admin == null) {
        //    throw new RuntimeException("令牌无效");
       // }
        if (username==null || username.trim().length()==0)
        {
            throw new RuntimeException("用户名不存在");
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}
